import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import { h } from 'vue'

const Layout = () => import('@/views/Layout.vue')
const Home = () => import('@/views/home/index.vue')
const TopCategory = () => import('@/views/category/index.vue')
const HoSubCategory = () => import('@/views/category/sub.vue')
const Goods = () => import('@/views/goods/index')
const Cart = () => import('@/views/cart/index')

const Login = () => import('@/views/login/index')
const LoginCallback = () => import('@/views/login/callback')

const Checkout = () => import('@/views/member/pay/checkout')
const Pay = () => import('@/views/member/pay/index')
const PayResult = () => import('@/views/member/pay/result')

const MemberLayout = () => import('@/views/member/Layout')
const MemberHome = () => import('@/views/member/home')
const MemberOrder = () => import('@/views/member/order')
const MemberOrderDetail = () => import('@/views/member/order/detail.vue')

const routes = [
  // 一级路由规则
  {
    path: '/',
    component: Layout,
    // 二级路由规则
    children: [
      // 首页路由规则
      { path: '/', component: Home },
      // 头部的一级分类界面路由规则
      { path: '/category/:id', component: TopCategory },
      // 头部的二级分类界面路由规则
      { path: '/category/sub/:id', component: HoSubCategory },
      // 商品详情界面路由规则
      { path: '/product/:id', component: Goods },
      // 购物车界面路由规则
      { path: '/cart', component: Cart },
      // 订单界面路由规则
      { path: '/member/checkout', component: Checkout },
      // 支付前的界面路由规则
      { path: '/member/pay', component: Pay },
      // 支付结果路由规则
      { path: '/pay/callback', component: PayResult },
      // 个人中心路由规则
      {
        path: '/member',
        component: MemberLayout,
        children: [
          // 个人中心首页路由规则
          { path: '/member', component: MemberHome },
          // 订单详情列表界面路由规则
          // vue3嵌套路由写法，才能生效激活导航时的样式
          {
            path: '/member/order',
            component: { render: () => h(<RouterView />) },
            children: [
              { path: '', component: MemberOrder },
              { path: ':id', component: MemberOrderDetail }

            ]
          }

        ]
      }

    ]
  },
  // 登录界面路由规则
  { path: '/login', component: Login },
  // qq绑定账号界面路由规则
  { path: '/login/callback', component: LoginCallback }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 切换路由时自动回到顶部
  scrollBehavior (to, from, savedPosition) {
    // 返回位置对象
    return { top: 0 }
  }

})

// 全局导航守卫
router.beforeEach((to, from, next) => {
  // 没有登录时所以去往地址是以 /member 开头的界面都需要拦截
  const { profile } = store.state.user
  if (!profile && to.path.startsWith('/member')) {
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  }
  next()
})

export default router
